package ServiceProvider;

import java.io.*;
import java.net.*;
import java.util.Timer;

public class QuerySender extends Thread{

	private static final int TIMER_PERIOD = 5000;
	private static final int TIMER_DELAY = 5000;
	private boolean ifStopThread = true;
	private boolean ifSendSucc = false;
	
	private Socket querySocket;
	private PrintWriter sendWriter;
	private BufferedReader receiveReader;
	
	private Timer timer;
	private QueryHeartBeat heartBeat;
	private String queryContent;
	
	public QuerySender(String ip, String portString) {
		int port = Integer.parseInt(portString);
		
		try {
			querySocket = new Socket(ip, port);
			sendWriter = new PrintWriter(querySocket.getOutputStream());
			receiveReader = new BufferedReader(new InputStreamReader(querySocket.getInputStream()));
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		heartBeat = new QueryHeartBeat(this, sendWriter);
	}

	public void sendQueryContent(String queryContent) {
		if (this.queryContent == null)
			this.queryContent = queryContent;
		
		sendWriter.println(queryContent);
		sendWriter.flush();
		
		if (timer == null) {
			timer = new Timer();
			this.sendQueryContent("Feed");
			timer.schedule(heartBeat, TIMER_DELAY, TIMER_PERIOD);
		}
	}
	
	public boolean isSendingSuccessful() {
		return ifSendSucc;
	}
	
	public String getQueryContent() {
		return queryContent;
	}
	
	@Override
	public void run() {
		super.run();
		
		while (ifStopThread) {
			try {
				String received = receiveReader.readLine();
				heartBeat.setLastReceivedTime(System.currentTimeMillis());
				
				if (!received.equals("Back")) {
					System.out.println(received);
					ifStopThread = false;
					ifSendSucc = true;
				}
				
			} catch (IOException e) {
				e.printStackTrace();
			} 
		}
		
		try {
			sendWriter.close();
			receiveReader.close();
			querySocket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	
	public void close() {
		
		try {
			ifStopThread = false;
			sendWriter.close();
			receiveReader.close();
			querySocket.close();
			this.interrupt();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
